package com.xiao.hao.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.xiao.hao.config.UserConfig;
import com.xiao.hao.constant.NumberConstants;
import com.xiao.hao.convertor.XhProductConvertor;
import com.xiao.hao.convertor.XhProductUserConvertor;
import com.xiao.hao.entity.*;
import com.xiao.hao.exception.BusinessException;
import com.xiao.hao.facade.XhProductUserFacade;
import com.xiao.hao.mapper.*;
import com.xiao.hao.req.XhProductUserInsertReq;
import com.xiao.hao.req.XhProductUserQueryPageReq;
import com.xiao.hao.req.XhProductUserUpdateReq;
import com.xiao.hao.resp.XhProductResp;
import com.xiao.hao.utils.BaseId;
import com.xiao.hao.utils.PageResult;
import com.xiao.hao.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Description 用户用药计划关联表 服务实现层
 * @Author xiaohao
 * @Date 2025-03-04 11:24:49
 */
@Service
@Slf4j
public class XhProductUserServiceImpl implements XhProductUserFacade {

    @Resource
    XhProductUserMapper mapper;

    @Resource
    XhProductMapper xhProductMapper;

    @Resource
    XhMedicationPlanMapper xhMedicationPlanMapper;

    @Resource
    XhUserInfoFileMapper xhUserInfoFileMapper;


    @Resource
    XhAskAboutMapper xhAskAboutMapper;

    @Resource
    XhNutritionalPairingMapper xhNutritionalPairingMapper;

    /**
     * 功能描述: 角色新增
     *
     * @param req
     * @return com.xiao.hao.utils.Result
     * @author xiaohao
     * @date 2025-03-04 11:24:49
     */
    @Override
    public Result insert(XhProductUserInsertReq req) {
        XhAskAbout xhAskAbout = xhAskAboutMapper.selectOne(new LambdaQueryWrapper<XhAskAbout>().eq(XhAskAbout::getAge, req.getAge()).
                eq(XhAskAbout::getSex, req.getSex()).eq(XhAskAbout::getProblemCode, req.getProblemCode()));
        BusinessException.isTrue(ObjectUtil.isNotEmpty(xhAskAbout), "询问问题参数错误,请重新提交请求！！！");

        List<XhProduct> xhProducts = xhProductMapper.selectBatchIds(req.getProductIds());
        BusinessException.isTrue(CollUtil.isNotEmpty(xhProducts), "非法请求，产品数据不存在！！！");
        List<XhProductUser> xhProductUsers = mapper.selectList(new LambdaQueryWrapper<XhProductUser>()
                .in(XhProductUser::getProductId, req.getProductIds()).eq(XhProductUser::getUserInfoId, req.getUserInfoId())
                .eq(XhProductUser::getUserInfoFileId, req.getUserInfoFileId()));
        BusinessException.isTrue(CollUtil.isEmpty(xhProductUsers), "产品计划已经添加，请不要重复添加！！！");
        req.getProductIds().forEach(f -> {
            mapper.insert(XhProductUser.builder().productId(f).userInfoId(req.getUserInfoId()).userInfoFileId(req.getUserInfoFileId()).build());
        });
        List<XhNutritionalPairing> xhNutritionalPairings = xhNutritionalPairingMapper.selectList(new LambdaQueryWrapper<XhNutritionalPairing>().eq(XhNutritionalPairing::getThoughtProcessId, xhAskAbout.getId())
                .orderByAsc(XhNutritionalPairing::getId));

        List<XhNutritionalPairing> xhNutritionalPairings1 = xhNutritionalPairings.subList(3, xhNutritionalPairings.size());
        String collectz = xhNutritionalPairings1.stream().map(XhNutritionalPairing::getHeaderZ).collect(Collectors.joining(","));
        String collectw = xhNutritionalPairings1.stream().map(XhNutritionalPairing::getHeaderW).collect(Collectors.joining(","));
        String collectn = xhNutritionalPairings1.stream().map(XhNutritionalPairing::getHeaderN).collect(Collectors.joining(","));
        String collects = xhNutritionalPairings1.stream().map(XhNutritionalPairing::getHeaderS).collect(Collectors.joining(","));

//        XhUserInfoFile xhUserInfoFile = xhUserInfoFileMapper.selectOne(new LambdaQueryWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId())
//                .eq(XhUserInfoFile::getStatus, NumberConstants.INT_ONE));
        List<XhMedicationPlan> xhMedicationPlans = xhMedicationPlanMapper.selectList(new LambdaQueryWrapper<XhMedicationPlan>()
                .eq(XhMedicationPlan::getUserInfoFileId, req.getUserInfoFileId()));
        final Boolean[] flag1 = {false};
        xhProducts.forEach(x -> {
            List<String> tmpDate = Lists.newArrayList();
            if (ObjectUtil.isNotEmpty(xhMedicationPlans)) {
                String collect = xhMedicationPlans.stream().map(XhMedicationPlan::getMedicationName).collect(Collectors.joining(","));
                if (collect.indexOf(x.getProductName()) != -1) {
                    XhMedicationPlan xhMedicationPlan = xhMedicationPlans.stream().filter(f -> f.getMedicationName().equals(x.getProductName())).findFirst().get();
                    LocalDateTime localDateTime = xhMedicationPlan.getCreateTime().plusDays(7);
                    if (localDateTime.isAfter(LocalDateTime.now())) {
                        flag1[0] = true;
                    } else {
                        xhMedicationPlanMapper.deleteById(xhMedicationPlan.getId());
                    }
                }
            }
            if (flag1[0]) {
                return;
            }
            if (collectz.indexOf(x.getProductName()) != -1) {
                tmpDate.add("8:00");
            }
            if (collectw.indexOf(x.getProductName()) != -1) {
                tmpDate.add("12:00");
            }
            if (collectn.indexOf(x.getProductName()) != -1) {
                tmpDate.add("18:00");
            }
            if (collects.indexOf(x.getProductName()) != -1) {
                tmpDate.add("21:30");
            }

            XhMedicationPlan xhMedicationPlanTmp = XhMedicationPlan.builder().userInfoFileId(req.getUserInfoFileId()).medicationName(x.getProductName())
                    .startingMedication("7天").surgicalEnum(x.getSurgicalEnum()).medicationFrequency("隔天")
                    .medicationNum(tmpDate.size()).productDate(tmpDate.stream().collect(Collectors.joining(",")))
                    .eachDose(x.getEachDose()).eachDoseEum(x.getEachDoseEum()).medicationGuidance(x.getMedicationGuidance()).build();
            xhMedicationPlanMapper.insert(xhMedicationPlanTmp);
        });
        return Result.succeed();
    }


    /**
     * 功能描述: 角色修改
     *
     * @param req
     * @return com.xiao.hao.utils.Result
     * @author xiaohao
     * @date 2025-03-04 11:24:49
     */
    @Override
    public Result update(XhProductUserUpdateReq req) {
        return Result.succeed(mapper.updateById(XhProductUserConvertor.INSTANCE.reqToEntity(req)));
    }


    /**
     * 功能描述: 删除角色
     *
     * @param req
     * @return com.xiao.hao.utils.Result
     * @author xiaohao
     * @date 2025-03-04 11:24:49
     */
    @Override
    public Result delete(BaseId req) {
        mapper.delete(new LambdaQueryWrapper<XhProductUser>().eq(XhProductUser::getProductId, req.getId()).eq(XhProductUser::getUserInfoId, UserConfig.getUserId()));
        return Result.succeed();
    }

    /**
     * 功能描述: 角色分页查询
     *
     * @param req
     * @return com.xiao.hao.utils.PageResult
     * @author xiaohao
     * @date 2025-03-04 11:24:49
     */
    @Override
    public PageResult queryPage(XhProductUserQueryPageReq req) {
        Page<XhProductUser> page = mapper.selectPage(new Page(req.getNum(), req.getSize()), new LambdaQueryWrapper<XhProductUser>().orderByDesc(XhProductUser::getCreateTime));
        return PageResult.result(page.getTotal(), XhProductUserConvertor.INSTANCE.entityListToRespList(page.getRecords()));
    }

    @Override
    public Result queryProduct() {
        List<XhProduct> xhProducts = xhProductMapper.selectList(new LambdaQueryWrapper<XhProduct>().orderByAsc(XhProduct::getId));
        List<XhUserInfoFile> xhUserInfoFiles = xhUserInfoFileMapper.selectList(new LambdaQueryWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId())
                .eq(XhUserInfoFile::getType, NumberConstants.INT_ONE));
        if (CollUtil.isNotEmpty(xhUserInfoFiles)) {
            List<XhProductUser> xhProductUsers = mapper.selectList(new LambdaQueryWrapper<XhProductUser>().eq(XhProductUser::getUserInfoId, UserConfig.getUserId())
                    .eq(XhProductUser::getUserInfoFileId, xhUserInfoFiles.get(0).getId()));
            List<XhProductResp> xhProductResps = XhProductConvertor.INSTANCE.entityListToRespList(xhProducts);
            if (CollUtil.isNotEmpty(xhProductUsers)) {
                List<String> collect = xhProductUsers.stream().map(x -> String.valueOf(x.getProductId())).collect(Collectors.toList());
                List<XhProductResp> collect1 = xhProductResps.stream().filter(f -> collect.contains(f.getId())).collect(Collectors.toList());
                collect1.forEach(c -> {
                    c.setType(NumberConstants.INT_ONE);
                });
                return Result.succeed(collect1);
            }
        }
        return Result.succeed(null);
    }

    @Override
    public Result queryProductInfo(BaseId req) {
        List<XhProduct> xhProducts = xhProductMapper.selectList(new LambdaQueryWrapper<XhProduct>().orderByAsc(XhProduct::getId));
        List<XhProductUser> xhProductUsers = mapper.selectList(new LambdaQueryWrapper<XhProductUser>().eq(XhProductUser::getUserInfoId, UserConfig.getUserId())
                .eq(XhProductUser::getUserInfoFileId, req.getId()));
        List<XhProductResp> xhProductResps = XhProductConvertor.INSTANCE.entityListToRespList(xhProducts);
        if (CollUtil.isNotEmpty(xhProductUsers)) {
            List<String> collect = xhProductUsers.stream().map(x -> String.valueOf(x.getProductId())).collect(Collectors.toList());
            xhProductResps.forEach(x -> {
                if (collect.contains(x.getId())) {
                    x.setType(NumberConstants.INT_ONE);
                }
            });
        }
        return Result.succeed(xhProductResps);
    }

    @Override
    public Result queryProductAll() {
        List<XhProduct> xhProducts = xhProductMapper.selectList(new LambdaQueryWrapper<XhProduct>().orderByAsc(XhProduct::getCreateTime));
        List<XhProductResp> xhProductResps = XhProductConvertor.INSTANCE.entityListToRespList(xhProducts);
        return Result.succeed(xhProductResps);
    }

}



